package com.itdaan.portal.business.solr;

import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.BinaryRequestWriter;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import com.itdaan.portal.common.util.ApplicationProperty;
/**
 * @author www.itdaan.com
 */
public class SolrClient4RICH {

	//记录日志
	private static Logger logger = Logger.getLogger(SolrClient4RICH.class);
	//内容
	private static HttpSolrServer server;
	
	//启动服务
	public static void startServer() throws Exception{
		if(server != null){
			return;
		}
		ApplicationProperty.init();
		server = new HttpSolrServer(ApplicationProperty.getProperty("solr.server.richcontent"));
		server.setConnectionTimeout(1000);
		server.setDefaultMaxConnectionsPerHost(100);
		server.setMaxTotalConnections(100);
	}
	
	//添加文档
	public synchronized static boolean addDoc(Integer id,String content) throws SolrServerException, IOException{
			//创建输入文档
		SolrInputDocument doc = new SolrInputDocument();
		doc.setField("id", id);
		doc.setField("content", content);
		server.add(doc);
		server.commit();
		return true;
	}	
	
   /**
    * 查询单个文档
    * @param domain
    * @return
    */
   public static String queryOne(Integer id){
		SolrQuery query = new SolrQuery();
		query.setQuery("id:"+id);
		String content = "";
		try {
			QueryResponse response = server.query(query);
			SolrDocumentList docs = response.getResults();
			for(SolrDocument doc : docs){
				content = doc.get("content").toString();
				break;
			}
		} catch (Exception e) {
			logger.error("从solr根据id查询单个文档时遇到错误", e);
		}	   
		return content;
   }
	
	
	public static void clear() {
		server.setRequestWriter(new BinaryRequestWriter());
		try {
			server.deleteByQuery("*:*");
			server.commit();
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static void main(String[] args) {
		try {
			startServer();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
//		try {
//			addDoc(1, "dlsjdkfjskdflk");
//		} catch (SolrServerException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
		String content = queryOne(134);
		System.out.println(content);
	}
	
}
